
// 添加年
function addYear(date, years) {
  var d = new Date(date)
  d.setFullYear(d.getFullYear() + years)
  return d
}

// 添加月
function addMonth(date, months) {
  var d = new Date(date)
  d.setMonth(d.getMonth() + months)
  return d
} 

// 添加天数
function addDate(date, days) {
  var d = new Date(date)
  d.setDate(d.getDate() + days) 
  return d
} 

// 格式化日期 
function convertStringFromDate(date, format) {
  if (!date || !(date instanceof Date)) {
    return ""
  } 
  if (!format) {
    return date.toLocaleString()
  } 
  var mat = {};
  mat.M = date.getMonth() + 1//月份记得加1
  mat.H = date.getHours()
  mat.s = date.getSeconds()
  mat.m = date.getMinutes()
  mat.Y = date.getFullYear()
  mat.D = date.getDate()
  mat.d = date.getDay()//星期几
  mat.d = check(mat.d)
  mat.H = check(mat.H)
  mat.M = check(mat.M)
  mat.D = check(mat.D)
  mat.s = check(mat.s)
  mat.m = check(mat.m)  

  if (format.indexOf("yyyy") > -1){
    format = format.replace('yyyy', mat.Y)
  } else if (format.indexOf("yy") > -1){ 
    format = format.replace('yy', mat.Y.substring(1,3))
  }
  
  if (format.indexOf("MM") > -1) {
    format = format.replace('MM', mat.M)
  }

  if (format.indexOf("dd") > -1) {
    format = format.replace('dd', mat.D)
  }
  if (format.indexOf("HH") > -1) {
    format = format.replace('HH', mat.H)
  }
  if (format.indexOf("mm") > -1) {
    format = format.replace('mm', mat.m)
  }
  if (format.indexOf("ss") > -1) {
    format = format.replace('ss', mat.s)
  }
  return format 
}

//检查是不是两位数字，不足补全
function check(str) {
  str = str.toString();
  if (str.length < 2) {
    str = '0' + str;
  }
  return str;
}

// 日期改成字符串年月 
function convertDateFromString(dateString) {
  if (dateString) {
    var date = new Date(dateString.replace("-", "/"))
    return date;
  }
  return null
}

// 导出
module.exports = { 
  addYear: addYear,
  addMonth: addMonth,
  addDate: addDate,
  convertStringFromDate: convertStringFromDate, 
  convertDateFromString: convertDateFromString,
}

